package com.tanhua.manager.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVO;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.PublishVO;
import com.tanhua.domain.vo.UserInfoVO;
import com.tanhua.dubbo.api.*;
import com.tanhua.manager.domain.Freeze;
import com.tanhua.manager.domain.Unfreeze;
import com.tanhua.manager.mapper.FreezeMapper;
import com.tanhua.manager.mapper.UnfreezeMapper;
import com.tanhua.manager.vo.VideoVO;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

@Service
public class UserService {

    @Reference
    private UserApi userApi;

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private PublishApi publishApi;
    @Reference
    private CommentApi commentApi;
    @Reference
    private VideoApi videoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private FreezeMapper freezeMapper;

    @Autowired
    private UnfreezeMapper unfreezeMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户数据翻页
     * @param page
     * @param pagesize
     * @return
     */
    public ResponseEntity findUserList(int page, int pagesize) {
        //分页查询用户列表
        IPage<UserInfo> iPage = userInfoApi.finList(page, pagesize);
        //转换成PageResult
        PageResult<UserInfoVO> pageResult = new PageResult<>();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setPages((int) iPage.getPages());
        pageResult.setCounts((int) iPage.getTotal());
//        pageResult.setItems(iPage.getRecords());
        List<UserInfo> records = iPage.getRecords();
        List<UserInfoVO> volist = new ArrayList<>();
        for (UserInfo userInfo : records) {
            UserInfoVO vo = new UserInfoVO();
            //判断redis里冻结是否到期，如果到期，则添加字段userStatus的“1”，没到期则略过
            String phone = userApi.findById(userInfo.getId().intValue()).getMobile();
            String value = redisTemplate.opsForValue().get("FreezingTime" + phone);
            if (value == null) {
                //redis不存在，说明冻结到期，则解冻
                userInfo.setUserStatus("1");
                userInfoApi.update(userInfo);
                BeanUtils.copyProperties(userInfo, vo);
                vo.setAge(userInfo.getAge().toString());
                volist.add(vo);
                //还需要删除redis里面的冻结范围
                redisTemplate.delete("FreezingRange" + phone);
            } else {
                BeanUtils.copyProperties(userInfo, vo);
                vo.setAge(userInfo.getAge().toString());
                volist.add(vo);
            }
        }
        pageResult.setItems(volist);

        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity findUserById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        //判断redis里冻结是否到期，如果到期，则添加字段userStatus的“1”，没到期则略过
        String phone = userApi.findById(userId.intValue()).getMobile();
        String value = redisTemplate.opsForValue().get("FreezingTime" + phone);
        if (value == null && userInfo.getUserStatus().equals("2")) {
            //redis不存在，说明冻结到期，则解冻
            userInfo.setUserStatus("1");
            userInfoApi.update(userInfo);
            //还需要删除redis里面的冻结范围
            redisTemplate.delete("FreezingRange" + phone);
        }

        return ResponseEntity.ok(userInfo);
    }

    public ResponseEntity findPublishList(int page, int pagesize, Long uid, Long state) {
        PageResult pageResult = publishApi.findPublishList(page, pagesize, uid, state);
        List<Publish> publishList = pageResult.getItems();
        List<PublishVO> voList = new ArrayList<>();
        for (Publish publish : publishList) {
            PublishVO vo = new PublishVO();
            //动态发布人的信息封装到Vo对象
            UserInfo userInfo = userInfoApi.findById(publish.getUserId());
            BeanUtils.copyProperties(userInfo, vo);
            vo.setTags(userInfo.getTags().split(","));
            BeanUtils.copyProperties(publish, vo);
            vo.setId(publish.getId().toHexString());
            vo.setImageContent(publish.getMedias().toArray(new String[]{}));
            vo.setDistance("50米");
            vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));
            voList.add(vo);

        }
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity findPublishById(String publishId) {
        //查询publishId 对应的动态
        Publish publish = publishApi.findById(publishId);
        PublishVO vo = new PublishVO();
        // 转换成vo
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        BeanUtils.copyProperties(userInfo,vo);
        vo.setTags(userInfo.getTags().split(","));
        //查询动态的发布人信息 封装到vo对象里
        BeanUtils.copyProperties(publish, vo);
        vo.setId(publish.getId().toHexString());
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));


        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findCommentList(int page, int pagesize, String messageId) {
        //查看评论列表
        PageResult pageResult= commentApi.findComments(page, pagesize, messageId);
        //转换成vo
        List<Comment> commentList = pageResult.getItems();
        List<CommentVO> voList = new ArrayList<>();
        for (Comment comment : commentList) {
            CommentVO vo = new CommentVO();

            vo.setId(comment.getId().toHexString());
            vo.setContent(comment.getContent());
            vo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));

            UserInfo userInfo = userInfoApi.findById(comment.getUserId());
            BeanUtils.copyProperties(userInfo, vo);
            vo.setNickname(userInfo.getNickname());
            vo.setAvatar(userInfo.getAvatar());

            voList.add(vo);
        }
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity findVideoList(int page, int pagesize, Long uid) {
        PageResult pageResult = videoApi.findVideoListByUid(uid, page, pagesize);
        List<Video> videoList = pageResult.getItems();
        List<VideoVO> voList = new ArrayList<>();
        for (Video video : videoList) {
            VideoVO vo = new VideoVO();
            //补全 用户详情
            UserInfo userInfo = userInfoApi.findById(video.getUserId());
            vo.setAvatar(userInfo.getAvatar());
            BeanUtils.copyProperties(userInfo, vo);
            //补全 视频详情
            vo.setId(video.getId().toHexString());
            vo.setSignature(video.getText());
            vo.setCreateDate(new DateTime(video.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));

            voList.add(vo);
        }
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 动态拒绝
     * @param
     * @return
     */
    public ResponseEntity reject(String[] pids) {
        publishApi.reject(pids);
        Map<String, Object> map = new HashMap<>();
        map.put("message", "操作成功");
        return ResponseEntity.ok(map);
    }

    /**
     * 动态通过
     * @param publishIdList
     * @return
     */
    public ResponseEntity pass(String[] publishIdList) {
        publishApi.pass(publishIdList);

        Map<String, Object> map = new HashMap<>();
        map.put("message", "操作成功");
        return ResponseEntity.ok(map);
    }

    /**
     * 用户解冻操作
     * @param userId
     * @param reasonsForThawing
     * @return
     */
    public ResponseEntity unfreeze(Integer userId, String reasonsForThawing) {
        //1.获取当前用户的账户状态信息
        UserInfo userInfo = userInfoApi.findById(userId.longValue());
        //2.判断当前用户是否已经存在状态信息
        if (userInfo.getUserStatus() == null) {
            //为空则添加默认的正常状态
            userInfo.setUserStatus("1");
        } else if ("2".equals(userInfo.getUserStatus())) {
            //若存在，并且状态是2时，则代表冻结状态，需要解冻
            userInfo.setUserStatus("1");
            userInfoApi.update(userInfo);

            //补全数据
            Unfreeze unfreeze = new Unfreeze();
            unfreeze.setUserId(userId);
            unfreeze.setReasonsForThawing(reasonsForThawing);
            unfreeze.setCreated(new Date());
            unfreeze.setUpdated(new Date());
            Integer mock = unfreezeMapper.insert(unfreeze);
            //向redis保存解冻原因
            stringRedisTemplate.opsForValue().set("reasonsForThawing" + userId, reasonsForThawing);
            //删除redis中存储的冻结时间，冻结范围
            User user = userApi.findById(userId);
            String phone = user.getMobile();
            stringRedisTemplate.delete("FreezingTime" + phone);
            stringRedisTemplate.delete("FreezingRange" + phone);
            Map<String, Object> message = new HashMap<>();
            message.put("message", mock);
            return ResponseEntity.ok(message);
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 用户冻结操作
     * @param freeze
     * @return
     */
    public ResponseEntity freeze(Freeze freeze) {
        //1.查询当前准备冻结的账户
        Integer userId = freeze.getUserId();
        //2.判断当前是否是正常使用的状态
        UserInfo userInfo = userInfoApi.findById(userId.longValue());
        String phone = userApi.findById(userInfo.getId().intValue()).getMobile();
        if (userInfo.getUserStatus().equals("1")) {
            //正常使用状态，选择冻结时间
            switch (freeze.getFreezingTime()) {
                case 1:
                    //添加redis的冻结时间
                    redisTemplate.opsForValue()
                            .set("FreezingTime" + phone, "FreezingTime", Duration.ofSeconds(30));
                    //冻结id
                    Map<String, Object> message = getFreeze(freeze, userInfo);
                    return ResponseEntity.ok(message);
                case 2:
                    //添加redis的冻结时间
                    redisTemplate.opsForValue()
                            .set("FreezingTime" + phone, "FreezingTime", Duration.ofMinutes(1));
                    //冻结id
                    Map<String, Object> message1 = getFreeze(freeze, userInfo);
                    return ResponseEntity.ok(message1);
                case 3:
                    //添加redis的冻结时间
                    redisTemplate.opsForValue()
                            .set("FreezingTime" + phone, "FreezingTime");
                    Map<String, Object> message2 = getFreeze(freeze, userInfo);
                    return ResponseEntity.ok(message2);
            }
        }
        return null;
    }

    private Map<String, Object> getFreeze(Freeze freeze, UserInfo userInfo) {
        User user = userApi.findById(freeze.getUserId());
        String phone = user.getMobile();

        userInfo.setUserStatus("2");
        userInfoApi.update(userInfo);


        //冻结id
        freeze.setUserId(freeze.getUserId());
        //冻结时间
        freeze.setFreezingTime(freeze.getFreezingTime());
        if (redisTemplate.opsForValue().get("FreezingTime" + phone) != null) {
            //冻结范围
            switch (freeze.getFreezingRange()) {
                case 1:
                    //冻结范围是冻结登录
                    redisTemplate.opsForValue().set("FreezingRange" + phone, "1");
                    break;
                case 2:
                    //冻结范围是冻结发言
                    redisTemplate.opsForValue().set("FreezingRange" + phone, "2");
                    break;
                case 3:
                    //冻结范围是冻结发布动态
                    redisTemplate.opsForValue().set("FreezingRange" + phone, "3");
                    break;
                default:
                    freeze.setFreezingRange(freeze.getFreezingRange());
            }
        } else {
            redisTemplate.delete("FreezingRange" + phone);
        }

        //冻结原因
        freeze.setReasonsForFreezing(freeze.getReasonsForFreezing());
        //冻结备注
        freeze.setFrozenRemarks(freeze.getFrozenRemarks());
        //补全数据
        freeze.setCreated(new Date());
        freeze.setUpdated(new Date());

        Map<String, Object> message = new HashMap<>();
            //新增
            int mock = freezeMapper.insert(freeze);
            message.put("message", mock);
        return message;
    }

}
